package com.example.listener;


import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "mail")
public class MailQueueListener {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;

    //处理邮件发送
    @RabbitHandler
    public void sendMailMessage(Map<String, Object> data){
        String email = data.get("email").toString();
        Integer code = (Integer) data.get("code");
        String type = (String) data.get("type");
        SimpleMailMessage message = switch (type){
            case "register" ->
                createMessage("欢迎注册我们的网站"
                        , "您的邮箱验证码为："+code+"，有效时常3 min ，为了保障您的账户安全，请勿向他人泄露！"
                        ,email);

            case "reset" ->
                createMessage("您的重置密码邮件"
                        , "您正在进行重置密码操作，验证码为："+code+"，如非本人操作，请无视！"
                        ,email);
            case "modify" ->
                    createMessage("您的邮箱修改邮件"
                            , "您正在进行电子邮箱绑定操作，验证码为："+code+"，如非本人操作，请无视！"
                            ,email);
            default -> null;
        };
        if(message == null){
            return;
        }
        //发送构造好的邮件
        javaMailSender.send(message);
    }

    /**
     * 生成y一个邮件
     * @param title 标题
     * @param content 内容
     * @param email 目标
     * @return 邮件
     */
    private SimpleMailMessage createMessage(String title,String content,String email){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(title);
        message.setText(content);
        message.setTo(email);
        message.setFrom(username);
        return message;
    }

}
